package com.hch.netty.nacos;

import com.hch.netty.nacos.entity.AgreementEntity;
import com.hch.netty.nacos.entity.MarshallingCodeCFactory;
import com.hch.netty.nacos.entity.RespEntity;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * # @Time :2021/12/9 16:12
 * # @Author: HeCongHui
 */
public class ConsumerClient {
    private final String host;
    private final int port;
    private final String message;

    public ConsumerClient(String host, int port, String message) {
        this.host = host;
        this.port = port;
        this.message = message;
    }

    public void start() throws InterruptedException {
        connect(host, port, message);

    }

    private void connect(String host, int port, String msg) throws InterruptedException {
        // 1.创建一个 NioEventLoopGroup 对象实例
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 2.创建客户端启动引导/辅助类：Bootstrap
            Bootstrap b = new Bootstrap();
            // 3.指定线程组
            b.group(group)
                    // 4.指定 IO 模型
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(
                                    MarshallingCodeCFactory.buildMarshallingDecoder()
                            );
                            p.addLast(
                                    MarshallingCodeCFactory.buildMarshallingEncoder()
                            );
                            // 5.这里可以自定义消息的业务处理逻辑
                            ChannelPipeline entries = p.addLast(new ConsumerClientHandler(msg));
                        }
                    });
            // 6.尝试建立连接
            ChannelFuture f = b.connect(host, port).sync();
            // 7.等待连接关闭（阻塞，直到Channel关闭）
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private class ConsumerClientHandler extends ChannelInboundHandlerAdapter {

        private final String message;

        public ConsumerClientHandler(String message) {
            this.message = message;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            AgreementEntity agreementEntity = new AgreementEntity(1,
                    "mayikt-member", null);
            ctx.writeAndFlush(agreementEntity);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            RespEntity respEntity = (RespEntity) msg;
            System.out.println("消费者读取数据:" + respEntity.toString());
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            super.channelReadComplete(ctx);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ConsumerClient("127.0.0.1", 8009, null).start();
    }
}
